package com.jinlia.show.modules.base.system.service;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.jinlia.show.common.core.exception.MyRuntimeException;
import com.jinlia.show.modules.base.system.entity.PhoneMsg;
import com.jinlia.show.modules.base.system.mapper.PhoneMsgMapper;
import lombok.SneakyThrows;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLEncoder;
import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Random;

@Service
public class PhoneMsgMapperService extends ServiceImpl<PhoneMsgMapper, PhoneMsg> {

    Random random = new Random();
    /**
     * 发送验证码
     *
     * @param phoneNum
     * @return
     */
    public String sendVerifyCode(String phoneNum, String userId) {
        /**
         * 校验时间
         */
        List<PhoneMsg> list = this.lambdaQuery()
                .eq(PhoneMsg::getSender, userId)
                .eq(PhoneMsg::getSendToNum, phoneNum)
                .orderByDesc(PhoneMsg::getCreateTime)
                .list();
        if (!CollectionUtils.isEmpty(list) && list.get(0).getCreateTime().plusMinutes(3).isAfter(LocalDateTime.now())) {
            throw new MyRuntimeException("验证码已发送!!!,请稍后");
        }

        //发送短信
        HashMap<String, String> dataVale = new HashMap<>();
        dataVale.put("code", String.valueOf(random.nextInt(9000) + 1000));
        dataVale.put("sender", "1234");
        String s = authPhone(phoneNum, dataVale);
        PhoneMsg phoneMsg = new PhoneMsg();
        phoneMsg.setSender(userId);
        phoneMsg.setSendToNum(phoneNum);
        phoneMsg.setContent(dataVale.get("code"));
        phoneMsg.setTempId("code");
        boolean save = this.save(phoneMsg);
        return "1234";
    }

    public Boolean checkVerifyCode(String phoneNum, String userId, String code) {
        List<PhoneMsg> list = this.lambdaQuery()
                .eq(PhoneMsg::getSender, userId)
                .eq(PhoneMsg::getSendToNum, phoneNum)
                .eq(PhoneMsg::getContent, code)
                .orderByDesc(PhoneMsg::getCreateTime)
                .list();
        if (CollectionUtils.isEmpty(list)) {
            throw new MyRuntimeException("验证码不正确!!!");
        }
        if (!list.get(0).getCreateTime().plusMinutes(5).isAfter(LocalDateTime.now())) {
            throw new MyRuntimeException("验证码已过期!!!");
        }
        return Boolean.TRUE;
    }

    /**
     * 手机认证短信
     * @param mobile
     * @param dataVale
     * @return
     */
    public String authPhone(String mobile, Map<String, String> dataVale) {
        HashMap<String, String> paramDate = new HashMap<>();
        paramDate.put("mobile", mobile);
        paramDate.put("tpl_id", "263997");
        paramDate.put("key", "4e8db8350b275b9235155f880e3c33c6");
        paramDate.put("tpl_value", buildTplValue(dataVale));
        String urlGet = "http://v.juhe.cn/sms/send?" + urlEncodeParam(paramDate);
        return doGet(urlGet);
    }
    //将map型转为请求参数型
    @SneakyThrows
    public String buildTplValue(Map<String, String> data) {
        StringBuilder sb = new StringBuilder();
        for (Map.Entry i : data.entrySet()) {
            if ("sender".equals(i.getKey())) {
                continue;
            }
            sb.append("#").append(i.getKey()).append("#").append("=").append(i.getValue()).append("&");
        }
        sb.deleteCharAt(sb.length() - 1);
        return URLEncoder.encode(sb.toString(), "UTF-8");
    }
    /**
     * https://www.sdk.cn/details/lE5wmb52qGOo8DgojN?s=api
     *
     * @param httpUrl 请求地址
     * @return doGetResponse
     */
    public String doGet(String httpUrl) {
        HttpURLConnection connection = null;
        InputStream inputStream = null;
        BufferedReader bufferedReader = null;
        String result = null;// 返回结果字符串
        try {
            // 创建远程url连接对象
            URL url = new URL(httpUrl);
            // 通过远程url连接对象打开一个连接，强转成httpURLConnection类
            connection = (HttpURLConnection) url.openConnection();
            // 设置连接方式：get
            connection.setRequestMethod("GET");
            // 设置连接主机服务器的超时时间：15000毫秒
            connection.setConnectTimeout(15000);
            // 设置读取远程返回的数据时间：60000毫秒
            connection.setReadTimeout(60000);
            // 发送请求
            connection.connect();
            // 通过connection连接，获取输入流
            if (connection.getResponseCode() == 200) {
                inputStream = connection.getInputStream();
                // 封装输入流，并指定字符集
                bufferedReader = new BufferedReader(new InputStreamReader(inputStream, "UTF-8"));
                // 存放数据
                StringBuilder sbf = new StringBuilder();
                String temp;
                while ((temp = bufferedReader.readLine()) != null) {
                    sbf.append(temp);
                    sbf.append(System.getProperty("line.separator"));
                }
                result = sbf.toString();
            }
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            // 关闭资源
            if (null != bufferedReader) {
                try {
                    bufferedReader.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (null != inputStream) {
                try {
                    inputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (connection != null) {
                connection.disconnect();// 关闭远程连接
            }
        }
        return result;
    }
    //将map型转为请求参数型
    @SneakyThrows
    public String urlEncodeParam(Map<String, String> data) {
        StringBuilder sb = new StringBuilder();
        for (Map.Entry i : data.entrySet()) {
            sb.append(i.getKey()).append("=").append(i.getValue()).append("&");
        }
        sb.deleteCharAt(sb.length() - 1);
        return sb.toString();
    }

}
